package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.ybkj.daijia.CSRFTokenManager;
import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.MemberInBlackListEvent;
import com.ybkj.daijia.server.event.model.MemberRechargeEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.gasstation.Discount;
import com.ybkj.daijia.server.gasstation.GasStation;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.mc.PassengerAccount.PayType;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.mc.PassengerConcats;
import com.ybkj.daijia.server.mc.PassengerGrade;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.MemberLogin;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.UsuallyEmploy;
import com.ybkj.daijia.server.model.WeixinManager;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule.CouponType;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.GasDiscountService;
import com.ybkj.daijia.server.service.GasStationService;
import com.ybkj.daijia.server.service.MemberLoginRecordService;
import com.ybkj.daijia.server.service.MemberPaymentsRecordService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.UsuallyEmployService;
import com.ybkj.daijia.server.service.WeixinManagerService;
import com.ybkj.daijia.server.service.ZhuancheService;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "member")
public class MemberController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberPaymentsRecordService memberPaymentsRecordService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponRuleService couponRuleService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private WeixinManagerService weixinManagerService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private UsuallyEmployService usuallyEmployService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private GasStationService gasStationService;
    @Autowired
    private GasDiscountService gasDiscountService;
    @Autowired
    private MemberLoginRecordService memberLoginRecordService;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("grades", memberService.listAllGrades());
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            mv.setViewName("member/list");
            mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "listData", method = RequestMethod.GET)
    @ResponseBody
    public Page<Passenger> listData(
        @RequestParam(required = false, value = "type") Integer type[],
        @RequestParam(required = false, value = "gradeId") Long grade[],
        @RequestParam(required = false, value = "companyIds") Long companyIds[],
        @RequestParam(required = false, value = "permission") Boolean[] permission,
        @RequestParam(required = false, value = "isPlatform") Integer[] isPlatform,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "carNumber") String carNumber,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "introduceName") String introduceName) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("member")) {
            Page<Passenger> page = null;

            if (principal.isCompanyType()) {
                page = memberService
                    .findByMultiCondition(type, grade, companyIds, permission, isPlatform,
                        startTime, endTime, phone, name, carNumber, introduceName, Pager.getPage(),
                        Pager.getLimit());
            } else {
                page = memberService
                    .findByMultiCondition(type, grade, null, permission, isPlatform, startTime,
                        endTime, phone, name, carNumber, introduceName, Pager.getPage(),
                        Pager.getLimit());
            }
            return page;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "exportOrder", method = RequestMethod.GET)
    public void exportOrder(
        @RequestParam(required = false, value = "type") Integer type[],
        @RequestParam(required = false, value = "gradeId") Long grade[],
        @RequestParam(required = false, value = "companyIds") Long companyIds[],
        @RequestParam(required = false, value = "permission") Boolean[] permission,
        @RequestParam(required = false, value = "isPlatform") Integer[] isPlatform,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "carNumber") String carNumber,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "introduceName") String introduceName,
        HttpServletRequest req, HttpServletResponse response) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("memberexport")) {//导出权限

            Page<Passenger> page = null;
            if (principal.isCompanyType()) {
                page = memberService
                    .findByMultiCondition(type, grade, companyIds, permission, isPlatform,
                        startTime, endTime, phone, name, carNumber, introduceName, null, null);
            } else {
                page = memberService
                    .findByMultiCondition(type, grade, null, permission, isPlatform, startTime,
                        endTime, phone, name, carNumber, introduceName, null, null);
            }
            List<Passenger> list = page.getContent();
            List<List<String>> rowlist = new ArrayList<List<String>>();
//				Properties prop = PropertiesLoaderUtils.loadAllProperties("config.properties");
//				String paotui = prop.getProperty("function.paotui.open");
//				Boolean pao = Boolean.valueOf(paotui);
            String[] head = new String[13];
            head[0] = ("联系人");
            head[1] = ("是否上传监管平台");
            head[2] = ("企业名称");
            head[3] = ("客户来源");
            head[4] = ("手机号");
            head[5] = ("允许签单");
            head[6] = ("余额(可提现)");
            head[7] = ("余额(不可提现)");
            if (principal.isCompanyType()) {
                head[8] = ("所属公司");
            }
            head[9] = ("等级");

            head[10] = ("车牌号 / 客户信息");
            head[11] = ("推荐人");
            head[12] = ("注册时间");

            for (Passenger a : list) {
                List<String> celllist = new ArrayList<String>();
                celllist.add(a.getName());
                celllist.add(a.getUpStatus() == 1 ? "是" : "否");
                celllist.add(a.getEnterprise_name() == null ? "-" : a.getEnterprise_name());
                celllist.add(a.getChannel_name());
                celllist.add(UseAllDataUtil.useAllData(a.getPhone()));
                celllist.add(a.isAllowOverdraw() ? "是" : "否");
                if (a.getType().equals(Passenger.TYPE_PASSENGER)) {
                    celllist.add(a.getDrawMoney() == null ? "0" : a.getDrawMoney().toString());

                } else if (a.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    celllist.add("-");
                }
                if (a.getType().equals(Passenger.TYPE_PASSENGER)) {
                    celllist.add(a.getNodrawMoney() == null ? "0" : a.getNodrawMoney().toString());

                } else if (a.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    celllist.add("-");
                }
                if (principal.isCompanyType()) {
                    celllist.add(a.getCompanyName());
                }

                celllist.add(a.getGrade_name());

                celllist.add(a.getPlateNumber() == null ? "-" : a.getPlateNumber());
                if (StringUtils.isNotBlank(a.getIntroducer()) && null != a.getIntroduceType()) {
                    if (a.getIntroduceType().equals(Passenger.INTRODUCE_TYPE_PASSENGER)) {
                        celllist.add(a.getIntroducer() + "(客户推荐)");
                    } else if (a.getIntroduceType().equals(Passenger.INTRODUCE_TYPE_DRIVER)) {
                        celllist.add(a.getIntroducer() + "(服务人员推荐)");
                    }
                } else {
                    celllist.add("-");
                }
                celllist.add(a.getCreated());

                rowlist.add(celllist);

            }

            try {
                ExcelUtil.export(req, response, head, rowlist);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 根据公司id查询所有等级.
     */
    @RequestMapping(value = "findByCompany", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> findByCompany(Long companyId) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            map.put("success", true);

            List<PassengerGrade> list = memberService.findByCompany(companyId);

            if (!CollectionUtils.isEmpty(list)) {
                map.put("data", list);
            } else {
                map.put("data", null);
            }

        } catch (Exception ex) {
            map.put("success", false);
            ex.printStackTrace();
        }

        return map;
    }

    @RequestMapping(value = "addPersonal", method = RequestMethod.GET)
    public ModelAndView addPersonal(HttpSession session) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("memberedit")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));
            Principal principal = (Principal) subject.getPrincipal();
            mv.addObject("grades", memberService.findByCompany(principal.getCompanyId()));
//			mv.addObject("arealist", areaService.listAll());
            mv.setViewName("member/addpersonal");//个人用户
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "createPersonal", method = RequestMethod.POST)
    public @ResponseBody
    Result<Passenger> createPersonal(Model model, Passenger passenger, HttpServletRequest req,
        HttpSession session) {

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberedit")) {
            if (CSRFTokenManager.isValid(req)) {

                passenger.setCompanyId(principal.getCompanyId());
                passenger.setCompanyName(principal.getCompanyAbbreviation());
                passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
                result = memberService.createPersonal(passenger);

                if (result.isSuccess()) {
                    String detail =
                        "【%s】新增了个人用户【" + passenger.getName() + "(" + passenger.getPhone() + ")】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(result.getResult());
                    rVo.setActivityEvent(ActivityEvent.newRegister);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                } else {
                    result.setObject(CSRFTokenManager.getTokenForSession(session));
                }

                return result;
            } else {
                result.setMessage("不能重复添加");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "editPersonal/{id}", method = RequestMethod.GET)
    public ModelAndView editPersonal(HttpSession session, @PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();

            Passenger local = memberService.findOnePassenger(id);

            local.setAreaDaijia(areaService.findDaijiaByPassenger(local.getId()));
            local.setAreaPaotui(areaService.findPaotuiByPassenger(local.getId()));

            PassengerAddress passengerAddress = errandService
                .findPassengerToPlace(local.getId(), PassengerAddress.TYPE_ADDRESS_OTHER);
            if (null != passengerAddress) {
                local.setAddress(passengerAddress.getAddress());
            }

            List<PassengerConcats> concats = errandService.findPassengerConcats(local.getId());
            PassengerConcats passengerConcats = null;
            if (!CollectionUtils.isEmpty(concats)) {
                passengerConcats = concats.get(0);
            }
            if (null != passengerConcats) {
                local.setMemberEcn(passengerConcats.getName());
                local.setMemberEcp(passengerConcats.getPhone());
            }
            local.setPhoneShow(UseAllDataUtil.useAllData(local.getPhone()));
            mv.addObject("passenger", local);

            mv.addObject("grades", memberService.findByCompany(local.getCompanyId()));
            mv.addObject("companys", companyService.findAll());
//			mv.addObject("arealist", areaService.listAll());

            mv.addObject("ismain", principal.isCompanyType());

            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));

            mv.setViewName("member/editpersonal");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updatePersonal", method = RequestMethod.POST)
    public @ResponseBody
    Result<Passenger> updatePersonal(Model model, HttpServletRequest req, HttpSession session,
        Passenger passenger) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        if (subject.isPermitted("memberedit")) {
            if (CSRFTokenManager.isValid(req)) {

                Passenger local = memberService.findOnePassenger(passenger.getId());
                local.setName(passenger.getName());
                local.setPhone(passenger.getPhone());
                local.setGender(passenger.getGender());
                local.setGrade_id(passenger.getGrade_id());
                if (principal.isCompanyType()) {
                    local.setCompanyId(passenger.getCompanyId());
                }
                local.setAreaDaijiaId(passenger.getAreaDaijiaId());
                local.setIdcard(passenger.getIdcard());
                local.setEmail(passenger.getEmail());
                local.setChannel_name(passenger.getChannel_name());
                local.setIntroducer(passenger.getIntroducer());
                local.setIntroduceType(passenger.getIntroduceType());
                local.setAddress(passenger.getAddress());
                local.setPlateNumber(passenger.getPlateNumber());
                local.setMemo(passenger.getMemo());
                local.setAllowOverdraw(passenger.isAllowOverdraw());

                result = memberService.updatePersonal(local);

                if (result.isSuccess()) {
                    String detail =
                        "【%s】修改了个人用户【" + local.getName() + "(" + local.getPhone() + ")】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);
                }

                return result;
            } else {
                result.setMessage("不能重复修改");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "elistData", method = RequestMethod.GET)
    @ResponseBody
    public Page<Enterprise> elistData(
        @RequestParam(required = false, value = "gradeId") Long grade[],
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "address") String address) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            Page<Enterprise> page = null;
            if (principal.isCompanyType()) {
                page = memberService
                    .queryAllEnterpriseByParams(name, grade, address, companyName, startTime,
                        endTime);
            } else {
                page = memberService
                    .queryAllEnterpriseByParams(name, grade, address, null, startTime, endTime);
            }
            return page;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "elist", method = RequestMethod.GET)
    public ModelAndView elist() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("grades", memberService.listAllGrades());
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            mv.setViewName("member/elist");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "addEnterprise", method = RequestMethod.GET)
    public ModelAndView addEnterprise(HttpSession session) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));
            Principal principal = (Principal) subject.getPrincipal();
            mv.addObject("grades", memberService.findByCompany(principal.getCompanyId()));
//			mv.addObject("arealist", areaService.listAll());
            mv.setViewName("member/addenterprise");//个人用户
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "createEnterprise", method = RequestMethod.POST)
    public @ResponseBody
    Result<Enterprise> createEnterprise(Enterprise enterprise, Model model, HttpServletRequest req,
        HttpSession session) {

        Result<Enterprise> result = new Result<Enterprise>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            if (CSRFTokenManager.isValid(req)) {
                List<Passenger> list = new ArrayList<Passenger>();
                if (!CollectionUtils.isEmpty(enterprise.getPassengers())) {
                    for (Passenger pa : enterprise.getPassengers()) {
                        if (StringUtils.isNotBlank(pa.getPhone())) {
                            if (!hasTheSamePhone(list, pa)) {
                                Passenger oldpa = memberService
                                    .findOnePassengerByPhone(pa.getPhone());
                                if (null != oldpa) {
                                    //如果数据库已存在
                                    result.setMessage("手机号'" + pa.getPhone() + "'已经存在");
                                    result.setObject(CSRFTokenManager.getTokenForSession(session));
                                    return result;
                                } else {
                                    pa.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
                                    list.add(pa);
                                }
                            }
                        }
                    }
                }

                if (CollectionUtils.isEmpty(list)) {
                    result.setMessage("至少填写一条手机号");
                    result.setObject(CSRFTokenManager.getTokenForSession(session));
                    return result;
                }

                enterprise.setPassengers(list);
                result = memberService.createEnterprise(enterprise);

                if (result.isSuccess()) {
                    String detail = "【%s】新增了企业用户【" + enterprise.getName() + "】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    Enterprise e = memberService.findOneEnterprise(result.getResult().getId());
                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(e.getPassengers().get(0));
                    rVo.setActivityEvent(ActivityEvent.newRegister);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                } else {
                    result.setObject(CSRFTokenManager.getTokenForSession(session));
                }

                return result;
            } else {
                result.setMessage("不能重复添加");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "editEnterprise/{id}", method = RequestMethod.GET)
    public ModelAndView editEnterprise(HttpSession session, @PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();

            Enterprise local = memberService.findOneEnterprise(id);

            if (null != local && null != local.getPassengers()
                && local.getPassengers().size() > 0) {
                for (int i = 0; i < local.getPassengers().size(); i++) {
                    local.getPassengers().get(i).setPhoneShow(
                        UseAllDataUtil.useAllData(local.getPassengers().get(i).getPhone()));
                }
            }

            local.setAreaDaijia(areaService.findDaijiaByEnterprise(local.getId()));
            local.setAreaPaotui(areaService.findPaotuiByEnterprise(local.getId()));
            mv.addObject("enterprise", local);

            mv.addObject("grades", memberService.findByCompany(local.getCompanyId()));
            mv.addObject("companys", companyService.findAll());
//			mv.addObject("arealist", areaService.listAll());

            mv.addObject("ismain", principal.isCompanyType());

            mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME,
                CSRFTokenManager.getTokenForSession(session));

            mv.setViewName("member/editenterprise");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updateEnterprise", method = RequestMethod.POST)
    public @ResponseBody
    Result<Enterprise> updateEnterprise(
        Model model, HttpServletRequest req, HttpSession session,
        Enterprise enterprise) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Enterprise> result = new Result<Enterprise>();

        if (subject.isPermitted("member")) {
            if (CSRFTokenManager.isValid(req)) {
                Enterprise local = memberService.findOneEnterprise(enterprise.getId());

                List<Passenger> list = new ArrayList<Passenger>();
                if (!CollectionUtils.isEmpty(enterprise.getPassengers())) {
                    for (Passenger pa : enterprise.getPassengers()) {
                        if (StringUtils.isNotBlank(pa.getPhone())) {
                            if (!hasTheSamePhone(list, pa)) {
                                if (exists(pa.getPhone(), pa.getId())) {
                                    //如果数据库已存在
                                    result.setMessage("手机号'" + pa.getPhone() + "'已经存在");
                                    result.setObject(CSRFTokenManager.getTokenForSession(session));
                                    return result;
                                } else {
                                    list.add(pa);
                                }
                            }
                        }
                    }
                }

                local.setName(enterprise.getName());
                local.setAddress(enterprise.getAddress());
                local.setMemo(enterprise.getMemo());
                local.setAllowOverdraw(enterprise.isAllowOverdraw());
                local.setGrade_id(enterprise.getGrade_id());
                if (principal.isCompanyType()) {
                    local.setCompanyId(enterprise.getCompanyId());
                }
                local.setAreaDaijiaId(enterprise.getAreaDaijiaId());

                for (Passenger pa : list) {
                    pa.setEnterprise_id(local.getId());
                }

                local.setPassengers(list);

                result = memberService.updateEnterprise(local);

                if (result.isSuccess()) {
                    String detail = "【%s】修改了企业用户【" + local.getName() + "】";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);
                }

                return result;
            } else {
                result.setMessage("不能重复修改");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping("lock")
    public ModelAndView lock() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        ModelAndView mv = new ModelAndView();

        mv.setViewName("member/lock");
        if (principal.isCompanyType()) {
            mv.addObject("companys", companyService.findAll());
        }
        return mv;

    }

    @RequestMapping("locklistData")
    public @ResponseBody
    Page<MemberLogin> locklistData(@RequestParam(required = false, value = "param") String param) {
        if (StringUtils.isBlank(param)) {
            param = null;
        }
        try {
            return memberLoginRecordService.findLockingMember(param);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "unLock", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> unLock(String phone) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //查询该用户资料
            Map<String, Object> findLoginRecord = memberLoginRecordService.findLoginRecord(phone);
            //修改资料
            MemberLogin memberLogin = (MemberLogin) findLoginRecord.get("data");
            memberLogin.setSmsTime(null);
            memberLogin.setSmsVerifyFiled(0);
            memberLogin.setSmsVerifyFiledTime(null);
            memberLogin.setSmsNumDay(0);
            memberLogin.setPasswordVerifyFiled(0);
            memberLogin.setPasswordVerifyFiledTime(null);
            memberLogin.setIsLock(false);
            memberLogin.setLockMemo(null);
            memberLoginRecordService.updateLoginRecord(memberLogin);
            map.put("success", true);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            return map;
        }
    }

    /*	@RequestMapping(value="gradelist",method=RequestMethod.GET)
        public ModelAndView gradelist(){

            Subject subject = SecurityUtils.getSubject();

            if(subject.isPermitted("member")){
                ModelAndView mv = new ModelAndView();

                mv.addObject("grades",memberService.listAllGrades());

                mv.setViewName("member/gradelist");

                return mv;
            }
            else{
                throw new NoPermissionException();
            }
        }*/
    @RequestMapping("gradelist")
    public ModelAndView gradeList() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("member/gradelist");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("gradelistData")
    public @ResponseBody
    List<PassengerGrade> recordListData() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            List<PassengerGrade> grades = new ArrayList<PassengerGrade>();
            if (principal.isCompanyType()) {
                grades = memberService.listAllGrades();
            } else {
                grades = memberService.findByCompany(principal.getCompanyId());
            }

            return grades;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "addGrade", method = RequestMethod.GET)
    public ModelAndView addGrade() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            Principal principal = (Principal) subject.getPrincipal();
            mv.addObject("arealist", areaService.listAll());
            List<Company> list = new ArrayList<Company>();

            if (principal.isCompanyType()) {
                list = companyService.findAll();
            } else {
                list.add(companyService.findOne(principal.getCompanyId()));
            }

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            if (serviceSetting.isZhuanche()) {
                List<com.ybkj.daijia.server.zhuan.CarType> carTypes = new ArrayList<com.ybkj.daijia.server.zhuan.CarType>();
                carTypes = zhuancheService.queryCarTypeV4up(principal.getCompanyId());
                mv.addObject("carTypes", carTypes);
            }

            mv.addObject("companys", list);
            mv.addObject("companyId", principal.getCompanyId());
            mv.setViewName("member/addgrade");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "createGrade", method = RequestMethod.POST)
    public @ResponseBody
    Result<PassengerGrade> createGrade(PassengerGrade passengerGrade) {

        Result<PassengerGrade> result = new Result<PassengerGrade>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            if (passengerGrade.getCompanyId() != null) {
                Company company = companyService.findOne(passengerGrade.getCompanyId());
                passengerGrade.setCompanyName(company.getAbbreviation());
            }

            result = memberService.createGrade(passengerGrade);

            if (result.isSuccess()) {
                String detail = "【%s】新增了客户等级【" + passengerGrade.getName() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;

        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "editGrade/{id}", method = RequestMethod.GET)
    public ModelAndView editGrade(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();

            mv.addObject("passengerGrade", memberService.findOneGrade(id));
            if (ServiceUtil.checkOpen().isGasstation()) {
                Page<GasStation> page = gasStationService.queryStationByParams(null, null,
                    null, null, null, null, null);
                List<Discount> list = gasDiscountService.findBypassengerGreadeId(id);
                mv.addObject("page", page);
                mv.addObject("list", list);
            }
            mv.addObject("arealist", areaService.listAll());
            mv.setViewName("member/editgrade");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "queryGrade", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryGrade(@RequestParam("id") Long id) {
        Map<String, Object> map = new HashMap<String, Object>();
        PassengerGrade passengerGrade = memberService.findOneGrade(id);
        if (null != passengerGrade) {
            map.put("success", true);
            map.put("data", passengerGrade.getPassengerGradeAndAreas());
        } else {
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateGrade", method = RequestMethod.POST)
    public @ResponseBody
    Result<PassengerGrade> updateGrade(PassengerGrade passengerGrade) {

        Result<PassengerGrade> result = new Result<PassengerGrade>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("member")) {
            result = memberService.updateGrade(passengerGrade);
            if (result.isSuccess()) {
                String detail = "【%s】修改了客户等级【" + passengerGrade.getName() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }
/*	
	@RequestMapping(value="blacklist",method=RequestMethod.GET)
	public ModelAndView blacklist(
			@RequestParam(required=false,value="companyId")Long companyId,
			@RequestParam(required=false,value="param")String param){
		
		Subject subject = SecurityUtils.getSubject();
		Principal principal = (Principal) subject.getPrincipal();
		
		if(subject.isPermitted("blacklist")){
			ModelAndView mv = new ModelAndView();
			
			mv.addObject("page",memberService.queryAllBlack(companyId,param));
			if(principal.isCompanyType()){
				mv.addObject("companys",companyService.findAll());
			}
			
			mv.addObject("companyId",companyId);
			mv.addObject("param",param);
			
			mv.setViewName("member/blacklist");
			
			return mv;
		}
		else{
			throw new NoPermissionException();
		}
		
	}*/

    @RequestMapping("blacklist")
    public ModelAndView blacklist() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("blacklist")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("member/blacklist");
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("blacklistData")
    public @ResponseBody
    Page<Passenger> blacklistData(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("blacklist")) {
            Page<Passenger> page = null;
            if (principal.isCompanyType()) {
                page = memberService.queryAllBlack(companyId, param);
            } else {
                page = memberService.queryAllBlack(principal.getCompanyId(), param);
            }

            return page;
        } else {
            throw new NoPermissionException();
        }

    }

//	@RequestMapping(value="add",method=RequestMethod.GET)
//	public ModelAndView add(HttpSession session){
//		
//		Subject subject = SecurityUtils.getSubject();
//
//		if(subject.isPermitted("member")){
//			ModelAndView mv = new ModelAndView();
//			mv.addObject("member", new Member());
//			mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//			mv.addObject("arealist", areaService.listAll());
//			mv.setViewName("member/add");//个人用户
//			return mv;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="addCompany",method=RequestMethod.GET)
//	public ModelAndView addCompany(HttpSession session){
//		
//		Subject subject = SecurityUtils.getSubject();
//
//		if(subject.isPermitted("member")){
//			ModelAndView mv = new ModelAndView();
//			mv.addObject("member", new Member());
//			mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//			mv.addObject("arealist", areaService.listAll());
//			mv.setViewName("member/addcompany");//企业用户
//			return mv;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="addVip",method=RequestMethod.GET)
//		public ModelAndView addVip(HttpSession session){
//		
//		Subject subject = SecurityUtils.getSubject();
//	
//		if(subject.isPermitted("member")){
//			ModelAndView mv = new ModelAndView();
//			mv.addObject("member", new Member());
//			mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//			mv.addObject("arealist", areaService.listAll());
//			mv.setViewName("member/addvip");//vip用户
//			return mv;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="create",method=RequestMethod.POST)
//	public @ResponseBody Result<Member> create(Member member,Model model,HttpServletRequest req,HttpSession session){
//		
//		Result<Member> result=new Result<Member>();
//		result.setSuccess(false);
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				
//				if(null!=member.getMemberAccounts() && member.getMemberAccounts().size()>0){
//					MemberAccount ma=member.getMemberAccounts().get(0);
//					if(!ma.isEmpty()){
//						MemberAccount oldma=memberAccountService.findByPhone(ma.getPhone());
//						if(null!=oldma){
//							//如果数据库已存在
//							result.setMessage("手机号'"+ma.getPhone()+"'已经存在");
//							result.setErrorcode("0");
//							result.setObject(CSRFTokenManager.getTokenForSession(session));
//							result.setLongValue(oldma.getMemberId());
//							return result;
//						}
//					}
//					else{
//						result.setMessage("手机号不能为空");
//						result.setObject(CSRFTokenManager.getTokenForSession(session));
//						return result;
//					}
//				}
//				else{
//					result.setMessage("手机号不能为空");
//					result.setObject(CSRFTokenManager.getTokenForSession(session));
//					return result;
//				}
//				
//				member.setCompanyId(principal.getCompanyId());
//				
//				if(member.getIsOverdraw()){
//					member.setIsOverdraw(Boolean.TRUE);
//				}
//				else{
//					member.setIsOverdraw(Boolean.FALSE);
//				}
//				member.setVirtual(BigDecimal.ZERO);
//				member.setAlreadyMoney(BigDecimal.ZERO);
//				List<MemberAccount> list=member.getMemberAccounts();
//				
//				for (MemberAccount ma : list) {
//					ma.setName(member.getName());
//				}
//				
//				member.setType(Member.MEMBER_TYPE_COMMON);
//				memberService.createMember(member, list);
//				
//				String detail="【%s】新增了个人用户【"+member.getName()+"("+list.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				ReactorVo rVo=new ReactorVo();
//				rVo.setMember(member);
//				rVo.setPhone(list.get(0).getPhone());
//				rVo.setActivityEvent(ActivityEvent.newRegister);
//				ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
//				applicationEventMulticaster.multicastEvent(activityCheckEvent);
//				
//				result.setSuccess(true);
//				return result;
//			}
//			else{
//				result.setMessage("不能重复添加");
//				return result;
//			}
//		}
//		else{
//			result.setMessage("您没有该权限");
//			return result;
//		}
//		
//	}

//	@RequestMapping(value="createCompany",method=RequestMethod.POST)
//	public @ResponseBody Result<Member> createCompany(Member member,Model model,HttpServletRequest req,HttpSession session){
//		
//		Result<Member> result=new Result<Member>();
//		result.setSuccess(false);
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				List<MemberAccount> list =new ArrayList<MemberAccount>();
//				if(null!=member.getMemberAccounts()){
//					for (MemberAccount ma : member.getMemberAccounts()) {
//						if(!ma.isEmpty()){
//							if(!hasTheSamePhone(list,ma)){
//								MemberAccount oldma=memberAccountService.findByPhone(ma.getPhone());
//								if(null!=oldma){
//									//如果数据库已存在
//									result.setMessage("手机号'"+ma.getPhone()+"'已经存在");
//									result.setErrorcode("0");
//									result.setObject(CSRFTokenManager.getTokenForSession(session));
//									result.setLongValue(oldma.getMemberId());
//									return result;
//								}
//								else{
//									list.add(ma);
//								}
//							}
//						}
//					}
//				}
//				
//				member.setCompanyId(principal.getCompanyId());
//				
//				if(member.getIsOverdraw()){
//					member.setIsOverdraw(Boolean.TRUE);
//				}
//				else{
//					member.setIsOverdraw(Boolean.FALSE);
//				}
//				member.setVirtual(BigDecimal.ZERO);
//				member.setType(Member.MEMBER_TYPE_COMPANY);
//				
//				member=memberService.createMember(member, list);
//				
//				String detail="【%s】新增了企业用户【"+member.getName()+"("+list.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				ReactorVo rVo=new ReactorVo();
//				rVo.setMember(member);
//				rVo.setPhone(list.get(0).getPhone());
//				rVo.setActivityEvent(ActivityEvent.newRegister);
//				ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
//				applicationEventMulticaster.multicastEvent(activityCheckEvent);
//				
//				result.setSuccess(true);
//				return result;
//			}
//			else{
//				result.setMessage("不能重复添加");
//				return result;
//			}
//		}
//		else{
//			result.setMessage("您没有该权限");
//			return result;
//		}
//		
//	}

//	@RequestMapping(value="createVip",method=RequestMethod.POST)
//	public @ResponseBody Result<Member> createVip(Member member,Model model,HttpServletRequest req,HttpSession session){
//		
//		Result<Member> result=new Result<Member>();
//		result.setSuccess(false);
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				if(null!=member.getMemberAccounts() && member.getMemberAccounts().size()>0){
//					MemberAccount ma=member.getMemberAccounts().get(0);
//					if(!ma.isEmpty()){
//						MemberAccount oldma=memberAccountService.findByPhone(ma.getPhone());
//						if(null!=oldma){
//							//如果数据库已存在
//							result.setMessage("手机号'"+ma.getPhone()+"'已经存在");
//							result.setErrorcode("0");
//							result.setObject(CSRFTokenManager.getTokenForSession(session));
//							result.setLongValue(oldma.getMemberId());
//							return result;
//						}
//					}
//					else{
//						result.setMessage("手机号不能为空");
//						result.setObject(CSRFTokenManager.getTokenForSession(session));
//						return result;
//					}
//				}
//				else{
//					result.setMessage("手机号不能为空");
//					result.setObject(CSRFTokenManager.getTokenForSession(session));
//					return result;
//				}
//				
//				if(StringUtils.isNotBlank(member.getIdCard())){
//					if(IdcardExists(member.getIdCard(),null)){
//						result.setMessage("身份证"+member.getIdCard()+"已经存在");
//						result.setObject(CSRFTokenManager.getTokenForSession(session));
//						return result;
//					}
//				}
//				
//				if(StringUtils.isNotBlank(member.getEmail())){
//					if(EmailExists(member.getEmail(),null)){
//						result.setMessage("电子邮件"+member.getEmail()+"已经存在");
//						result.setObject(CSRFTokenManager.getTokenForSession(session));
//						return result;
//					}
//				}
//				
//				member.setCompanyId(principal.getCompanyId());
//				
//				if(member.getIsOverdraw()){
//					member.setIsOverdraw(Boolean.TRUE);
//				}
//				else{
//					member.setIsOverdraw(Boolean.FALSE);
//				}
//				member.setVirtual(BigDecimal.ZERO);
//				
//				List<MemberAccount> list=member.getMemberAccounts();
//				for (MemberAccount ma : list) {
//					ma.setName(member.getName());
//				}
//				
//				member.setType(Member.MEMBER_TYPE_VIP);
//				member=memberService.createMember(member, list);
//				
//				String detail="【%s】新增了VIP用户【"+member.getName()+"("+list.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				//新注册活动
//				ReactorVo rVo=new ReactorVo();
//				rVo.setMember(member);
//				rVo.setPhone(list.get(0).getPhone());
//				rVo.setActivityEvent(ActivityEvent.newRegister);
//				ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
//				applicationEventMulticaster.multicastEvent(activityCheckEvent);
//				
//				result.setSuccess(true);
//				return result;
//			}
//			else{
//				result.setMessage("不能重复添加");
//				return result;
//			}
//		}
//		else{
//			result.setMessage("您没有该权限");
//			return result;
//		}
//		
//	}

    private boolean hasTheSamePhone(List<Passenger> list, Passenger p) {
        for (Passenger passenger : list) {
            if (passenger.getPhone().equals(p.getPhone())) {
                return true;
            }
        }
        return false;
    }

//	@RequestMapping(value="edit/{id}",method=RequestMethod.GET)
//	public ModelAndView edit(HttpSession session,@PathVariable("id")Long id,
//			@RequestParam(required=false,value="typechange")String typechange){
//
//		Subject subject = SecurityUtils.getSubject();
//
//		if(subject.isPermitted("member")){
//			ModelAndView mv = new ModelAndView();
//			
//			Member local = memberService.findOne(id);
//			local.setCompany(companyService.findOne(local.getCompanyId()));
//			local.setMemberAccounts(memberAccountService.findByMember(local.getId()));
//			
//			mv.addObject("member", local);
//			
//			mv.addObject("companys", companyService.findAll());
//			
//			mv.addObject("arealist", areaService.listAll());
//			
//			mv.addObject("typechange",typechange);
//			
//			mv.addObject(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//			
//			mv.setViewName("member/edit");
//			
//			if(StringUtils.isBlank(typechange)){
//				if(Member.MEMBER_TYPE_COMPANY.equals(local.getType())){
//					mv.setViewName("member/editcompany");
//				}
//				else if(Member.MEMBER_TYPE_VIP.equals(local.getType())){
//					mv.setViewName("member/editvip");
//				}
//			}
//			else{
//				if("1".equals(typechange)){
//					mv.setViewName("member/editcompany");
//				}
//				else if("2".equals(typechange)){
//					mv.setViewName("member/editvip");
//				}
//			}
//			
//			return mv;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="update",method=RequestMethod.POST)
//	public String update(Model model,HttpServletRequest req,HttpSession session,
//			Member member,Long companyId,Long areaId,Long areaCarId,
//			@RequestParam(required=false,value="typechange")String typechange,
//			@RequestParam(required=false,value="allowsign")boolean allowsign){
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				model.addAttribute("typechange", typechange);
//				
//				Member local = memberService.findOne(member.getId());
//				
//				if(null!=member.getMemberAccounts() && member.getMemberAccounts().size()>0){
//					MemberAccount ma=member.getMemberAccounts().get(0);
//					if(!ma.isEmpty()){
//						if(exists(ma.getPhone(),ma.getId())){
//							//如果数据库已存在
//							model.addAttribute("message", "手机号'"+ma.getPhone()+"'已经存在");
//							model.addAttribute("member", member);
//							model.addAttribute("companys", companyService.findAll());
//							model.addAttribute("arealist", areaService.listAll());
//							model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//							return "member/edit";
//						}
//						else{
//							MemberAccount dbma=memberAccountService.findOne(ma.getId());
//							dbma.setName(member.getName());
//							dbma.setPhone(ma.getPhone());
//							dbma.setAddress(ma.getAddress());
//							dbma.setCarNumber(ma.getCarNumber());
//							memberAccountService.updateByPrimaryKey(dbma);
//						}
//					}
//					else{
//						model.addAttribute("message", "手机号不能为空");
//						model.addAttribute("member", member);
//						model.addAttribute("companys", companyService.findAll());
//						model.addAttribute("arealist", areaService.listAll());
//						model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//						return "member/edit";
//					}
//				}
//				else{
//					model.addAttribute("message", "手机号不能为空");
//					model.addAttribute("member", member);
//					model.addAttribute("companys", companyService.findAll());
//					model.addAttribute("arealist", areaService.listAll());
//					model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//					return "member/edit";
//				}
//				
//				local.setName(member.getName());
//				local.setFromSource(member.getFromSource());
//				local.setIntroducer(member.getIntroducer());
//				local.setIntroduceType(member.getIntroduceType());
//				local.setMemo(member.getMemo());
//				
//				if(allowsign){
//					if(member.getIsOverdraw()){
//						local.setIsOverdraw(Boolean.TRUE);
//					}
//					else{
//						local.setIsOverdraw(Boolean.FALSE);
//					}
//				}
//				
//				
//				local.setType(Member.MEMBER_TYPE_COMMON);
//				local.setCompanyId(companyId);
//				local.setAreaId(areaId);
//				local.setAreaCarId(areaCarId);
//				
//				memberService.updateByPrimaryKey(local);
//				
//				List<MemberAccount> memberAccounts = memberAccountService.findByMember(local.getId());
//				
//				String detail="【%s】修改了个人用户【"+local.getName()+"("+memberAccounts.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				return "redirect:list";
//			}
//			else{
//				throw new IllegalArgumentException("CSRFTokenError");
//			}
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="updateCompany",method=RequestMethod.POST)
//	public String updateCompany(
//			Model model,HttpServletRequest req,HttpSession session,
//			Member member,Long companyId,Long areaId,Long areaCarId,
//			@RequestParam(required=false,value="typechange")String typechange,
//			@RequestParam(required=false,value="allowsign")boolean allowsign){
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				model.addAttribute("typechange", typechange);
//				
//				Member local = memberService.findOne(member.getId());
//				
//				List<MemberAccount> list =new ArrayList<MemberAccount>();
//				if(null!=member.getMemberAccounts()){
//					for (MemberAccount ma : member.getMemberAccounts()) {
//						if(!ma.isEmpty()){
////							if(!hasTheSamePhone(list,ma)){
////								if(exists(ma.getPhone(),ma.getId())){
////									//如果数据库已存在
////									model.addAttribute("message", "手机号'"+ma.getPhone()+"'已经存在");
////									member.setCompany(companyService.findOne(local.getCompanyId()));
////									member.setMemberAccounts(memberAccountService.findByMember(local.getId()));
////									model.addAttribute("member", member);
////									model.addAttribute("companys", companyService.findAll());
////									model.addAttribute("arealist", areaService.listAll());
////									model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
////									return "member/editcompany";
////								}
////								else{
////									ma.setId(null);
////									list.add(ma);
////								}
////							}
//						}
//					}
//				}
//				
//				local.setName(member.getName());
//				local.setFromSource(member.getFromSource());
//				local.setIntroducer(member.getIntroducer());
//				local.setIntroduceType(member.getIntroduceType());
//				local.setAgencyName(member.getAgencyName());
//				local.setAgencyAddress(member.getAgencyAddress());
//				local.setMemo(member.getMemo());
//				
//				if(allowsign){
//					if(member.getIsOverdraw()){
//						local.setIsOverdraw(Boolean.TRUE);
//					}
//					else{
//						local.setIsOverdraw(Boolean.FALSE);
//					}
//				}
//				
//				
//				for (MemberAccount ma : list) {
//					ma.setMemberId(local.getId());
//				}
//
//				local.setType(Member.MEMBER_TYPE_COMPANY);
//				local.setCompanyId(companyId);
//				local.setAreaId(areaId);
//				local.setAreaCarId(areaCarId);
//				memberService.updateByWithAccounts(local,list);
//				
//				String detail="【%s】修改了企业用户【"+local.getName()+"("+list.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				return "redirect:list?type=1";
//			}
//			else{
//				throw new IllegalArgumentException("CSRFTokenError");
//			}
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

//	@RequestMapping(value="updateVip",method=RequestMethod.POST)
//	public String updateVip(
//			Model model,HttpServletRequest req,HttpSession session,
//			Member member,Long companyId,Long areaId,Long areaCarId,
//			@RequestParam(required=false,value="typechange")String typechange,
//			@RequestParam(required=false,value="allowsign")boolean allowsign){
//		
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//		
//		if(subject.isPermitted("member")){
//			if(CSRFTokenManager.isValid(req)){
//				model.addAttribute("typechange", typechange);
//				
//				Member local = memberService.findOne(member.getId());
//				
//				if(null!=member.getMemberAccounts() && member.getMemberAccounts().size()>0){
//					MemberAccount ma=member.getMemberAccounts().get(0);
//					if(!ma.isEmpty()){
//						if(exists(ma.getPhone(),ma.getId())){
//							//如果数据库已存在
//							model.addAttribute("message", "手机号'"+ma.getPhone()+"'已经存在");
//							model.addAttribute("member", member);
//							model.addAttribute("companys", companyService.findAll());
//							model.addAttribute("arealist", areaService.listAll());
//							model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//							return "member/editvip";
//						}
//						else{
//							MemberAccount dbma=memberAccountService.findOne(ma.getId());
//							dbma.setName(member.getName());
//							dbma.setPhone(ma.getPhone());
//							dbma.setAddress(ma.getAddress());
//							dbma.setCarNumber(ma.getCarNumber());
//							memberAccountService.updateByPrimaryKey(dbma);
//						}
//					}
//					else{
//						model.addAttribute("message", "手机号不能为空");
//						model.addAttribute("member", member);
//						model.addAttribute("companys", companyService.findAll());
//						model.addAttribute("arealist", areaService.listAll());
//						model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//						return "member/editvip";
//					}
//				}
//				else{
//					model.addAttribute("message", "手机号不能为空");
//					model.addAttribute("member", member);
//					model.addAttribute("companys", companyService.findAll());
//					model.addAttribute("arealist", areaService.listAll());
//					model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//					return "member/editvip";
//				}
//				
//				if(StringUtils.isNotBlank(member.getIdCard())){
//					if(IdcardExists(member.getIdCard(),member.getId())){
//						model.addAttribute("message", "身份证"+member.getIdCard()+"已经存在");
//						model.addAttribute("member", member);
//						model.addAttribute("companys", companyService.findAll());
//						model.addAttribute("arealist", areaService.listAll());
//						model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//						return "member/editvip";
//					}
//				}
//				
//				if(StringUtils.isNotBlank(member.getEmail())){
//					if(EmailExists(member.getEmail(),member.getId())){
//						model.addAttribute("message", "电子邮件"+member.getEmail()+"已经存在");
//						model.addAttribute("member", member);
//						model.addAttribute("companys", companyService.findAll());
//						model.addAttribute("arealist", areaService.listAll());
//						model.addAttribute(CSRFTokenManager.CSRF_PARAM_NAME, CSRFTokenManager.getTokenForSession(session));
//						return "member/editvip";
//					}
//				}
//				
//				local.setName(member.getName());
//				local.setFromSource(member.getFromSource());
//				local.setIntroducer(member.getIntroducer());
//				local.setIntroduceType(member.getIntroduceType());
//				local.setIdCard(member.getIdCard());
//				local.setEmail(member.getEmail());
//				local.setMemo(member.getMemo());
//				
//				if(allowsign){
//					if(member.getIsOverdraw()){
//						local.setIsOverdraw(Boolean.TRUE);
//					}
//					else{
//						local.setIsOverdraw(Boolean.FALSE);
//					}
//				}
//				
//				local.setType(Member.MEMBER_TYPE_VIP);
//				local.setCompanyId(companyId);
//				local.setAreaId(areaId);
//				local.setAreaCarId(areaCarId);
//				memberService.updateByPrimaryKey(local);
//				
//				List<MemberAccount> memberAccounts = memberAccountService.findByMember(member.getId());
//				
//				String detail="【%s】修改了VIP用户【"+local.getName()+"("+memberAccounts.get(0).getPhone()+")】";
//				OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//				applicationEventMulticaster.multicastEvent(operationLogEvent);
//				
//				return "redirect:list?type=2";
//			}
//			else{
//				throw new IllegalArgumentException("CSRFTokenError");
//			}
//		}
//		else{
//			throw new NoPermissionException();
//		}
//		
//	}

    @RequestMapping(value = "money/{id}", method = RequestMethod.GET)
    public ModelAndView money(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("membermoneyview")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/money");

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());

            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isEmpty(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isEmpty(startTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.MONTH, -1);
                    start = cl.getTime();
                } else {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            mv.addObject("start", start);
            mv.addObject("end", end);
            mv.addObject("passenger", memberService.findOnePassenger(id));
            mv.addObject("page", memberPaymentsRecordService
                .queryByPassenger(id, null, start, end, Pager.getPage(), Pager.getLimit()));

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "money", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<PassengerAccount> money(Long passengerId, BigDecimal money, String memo) {

        Result<PassengerAccount> result = new Result<PassengerAccount>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("membermoney")) {
            if (money.compareTo(BigDecimal.ZERO) != 0) {

                PayType payType = PayType.RECHARGE_TYPE_ADMIN;
                if (money.compareTo(BigDecimal.ZERO) == -1) {
                    payType = PayType.PAYTYPE_ADMIN;
                }

                Passenger passenger = memberService.findOnePassenger(passengerId);
                result = memberService
                    .money(passenger, null, money, memo, principal.getUsername(), payType, null,
                        null, null, null, true, false);

                if (result.isSuccess()) {
                    ReactorVo rVo = new ReactorVo();
                    rVo.setPassenger(passenger);
                    rVo.setMoney(money);
                    rVo.setType("admin");
                    MemberRechargeEvent rechargeEvent = new MemberRechargeEvent(rVo);
                    applicationEventMulticaster.multicastEvent(rechargeEvent);

                    ReactorVo rVo2 = new ReactorVo();
                    rVo2.setPassenger(passenger);
                    rVo2.setMoney(money);
                    rVo2.setActivityEvent(ActivityEvent.recharging);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo2);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);

                    String detail = "【%s】为用户【" + passenger.getName() + "】充值了：" + money + "";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);
                }

                return result;
            } else {
                result.setMessage("请填写金额");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "moneyEnterprise/{id}", method = RequestMethod.GET)
    public ModelAndView moneyEnterprise(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("membermoney")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/emoney");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());

            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isEmpty(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isEmpty(startTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.MONTH, -1);
                    start = cl.getTime();
                } else {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            mv.addObject("start", start);
            mv.addObject("end", end);
            mv.addObject("enterprise", memberService.findOneEnterprise(id));
            mv.addObject("page", memberPaymentsRecordService
                .queryByEnterprise(id, null, start, end, Pager.getPage(), Pager.getLimit()));

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "moneyEnterprise", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<PassengerAccount> moneyEnterprise(Long enterpriseId, BigDecimal money, String memo) {

        Result<PassengerAccount> result = new Result<PassengerAccount>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("membermoney")) {
            if (money.compareTo(BigDecimal.ZERO) != 0) {

                PayType payType = PayType.RECHARGE_TYPE_ADMIN;
                if (money.compareTo(BigDecimal.ZERO) == -1) {
                    payType = PayType.PAYTYPE_ADMIN;
                }

                Enterprise enterprise = memberService.findOneEnterprise(enterpriseId);
                result = memberService
                    .moneyEnterprise(enterprise, money, memo, principal.getUsername(), payType,
                        null, null, null, null, true, false);

                if (result.isSuccess()) {
                    List<Passenger> passengers = enterprise.getPassengers();
                    if (!CollectionUtils.isEmpty(passengers)) {
                        ReactorVo rVo = new ReactorVo();
                        rVo.setPassenger(passengers.get(0));
                        rVo.setMoney(money);
                        rVo.setType("admin");
                        MemberRechargeEvent rechargeEvent = new MemberRechargeEvent(rVo);
                        applicationEventMulticaster.multicastEvent(rechargeEvent);
                    }

                    String detail = "【%s】为企业【" + enterprise.getName() + "】充值了：" + money + "";
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);
                }

                return result;
            } else {
                result.setMessage("请填写金额");
                return result;
            }
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "paymentsExport/{id}", method = RequestMethod.GET)
    public void paymentsExport(@PathVariable("id") Long id, HttpServletRequest req,
        HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("membermoney")) {

            List<PassengerAccount> list = new ArrayList<>();

            Passenger passenger = memberService.findOnePassenger(id);
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                list = memberPaymentsRecordService
                    .queryByPassenger(passenger.getId(), null, null, null, null, null).getContent();
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                list = memberPaymentsRecordService
                    .queryByEnterprise(passenger.getEnterprise_id(), null, null, null, null, null)
                    .getContent();
            }

            String[] heards = {"时间", "订单号", "金额(元)", "可提现余额(元)", "不可提现余额(元)", "充值/消费方式", "操作人",
                "备注"};

            List<List<String>> rowlist = new ArrayList<>();

            for (PassengerAccount c : list) {

                List<String> celllist = new ArrayList<>();

                celllist.add(DateFormatUtils.format(c.getCreated(), "yyyy-MM-dd HH:mm"));

                celllist.add(c.getOrderNo());

                if (c.getMoney().doubleValue() > 0) {
                    celllist.add("+" + c.getMoney().toString());
                } else if (c.getMoney().doubleValue() <= 0) {
                    celllist.add(c.getMoney().toString());
                }

                celllist.add(c.getAfterDrawMoney().toString());

                celllist.add(c.getAfterNoDrawMoney().toString());

                celllist.add(c.getPayTypeStr());

                celllist.add(c.getOperator());

                celllist.add(c.getDetails());

                rowlist.add(celllist);
            }

            ExcelUtil.export(req, response, heards, rowlist);

        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "paymentsEnterpriseExport/{id}", method = RequestMethod.GET)
    public void paymentsEnterpriseExport(@PathVariable("id") Long id, HttpServletRequest req,
        HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("membermoney")) {

            List<PassengerAccount> list = memberPaymentsRecordService
                .queryByEnterprise(id, null, null, null, null, null).getContent();

            String[] heards = {"时间", "订单号", "金额(元)", "可提现余额(元)", "不可提现余额(元)", "充值/消费方式", "操作人",
                "备注"};

            List<List<String>> rowlist = new ArrayList<>();

            for (PassengerAccount c : list) {

                List<String> celllist = new ArrayList<>();

                celllist.add(DateFormatUtils.format(c.getCreated(), "yyyy-MM-dd HH:mm"));

                celllist.add(c.getOrderNo());

                if (c.getMoney().doubleValue() > 0) {
                    celllist.add("+" + new BigDecimal(c.getMoney()));
                } else if (c.getMoney().doubleValue() <= 0) {
                    celllist.add(new BigDecimal(c.getMoney()).toString());
                }

                celllist.add(new BigDecimal(c.getAfterDrawMoney()).toString());

                celllist.add(new BigDecimal(c.getAfterNoDrawMoney()).toString());

                celllist.add(c.getPayTypeStr());

                celllist.add(c.getOperator());

                celllist.add(c.getDetails());

                rowlist.add(celllist);
            }

            ExcelUtil.export(req, response, heards, rowlist);

        } else {
            throw new NoPermissionException();
        }

    }

//	@RequestMapping(value = "inandout/{id}", method = RequestMethod.GET)
//	public ModelAndView inandout(
//			@PathVariable("id") Long id,
//			@RequestParam(required = false, value = "type") Long type,
//			@RequestParam(required = false, value = "startTime") String startTime,
//			@RequestParam(required = false, value = "endTime") String endTime)
//			throws ParseException {
//
//		Subject subject = SecurityUtils.getSubject();
//		
//		if(subject.isPermitted("member")){
//			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//			String now = formatter.format(new Date());
//
//			Date start = null;
//			Date end = null;
//			if (StringUtils.isEmpty(endTime)) {
//				Calendar cl = Calendar.getInstance();
//				cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
//				cl.add(Calendar.HOUR_OF_DAY, 23);
//				cl.add(Calendar.MINUTE, 59);
//				cl.add(Calendar.SECOND, 59);
//				end = cl.getTime();
//			} else {
//				Calendar cl = Calendar.getInstance();
//				cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
//				cl.add(Calendar.HOUR_OF_DAY, 23);
//				cl.add(Calendar.MINUTE, 59);
//				cl.add(Calendar.SECOND, 59);
//				end = cl.getTime();
//			}
//
//			if (StringUtils.isEmpty(startTime)) {
//				Calendar cl = Calendar.getInstance();
//				cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
//				cl.add(Calendar.MONTH, -1);
//				start = cl.getTime();
//			} else {
//				start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
//			}
//
//			ModelAndView mv = new ModelAndView();
//			mv.setViewName("member/inandout");
//			mv.addObject("member", memberService.findOne(id));
//
//			if (null != type && type == 1) {
//				// 充值记录
//				mv.addObject("page",
//						memberPaymentsRecordService.queryByMemberAndType(id, "recharge", start, end));
//				mv.addObject("type", 1);
//			} else {
//				// 消费记录
//				mv.addObject("page",
//						memberPaymentsRecordService.queryByMemberAndType(id, "consumed", start, end));
//				mv.addObject("type", 0);
//			}
//
//			mv.addObject("start", start);
//			mv.addObject("end", end);
//
//			return mv;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//
//	}

    @RequestMapping(value = "couponlist/{id}", method = RequestMethod.GET)
    public ModelAndView couponlist(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/couponlist");
            mv.addObject("passenger", memberService.findOnePassenger(id));

            Page<Coupon> page = couponService
                .queryByPassenger(id, Pager.getPage(), Pager.getLimit(), null);
            mv.addObject("page", page);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "findUsuallyEmploy/{id}", method = RequestMethod.GET)
    public ModelAndView findUsuallyEmploy(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/usuallyemploy");
            mv.addObject("passenger", memberService.findOnePassenger(id));

            List<UsuallyEmploy> list = usuallyEmployService
                .findUsuallyEmploy(id, Pager.getOffset(), Pager.getLimit());

            Long count = usuallyEmployService.countUsuallyEmploy(id);
            List<Driver> driverList = new ArrayList<Driver>();
            for (UsuallyEmploy usuallyEmploy : list) {
                Driver driver = driverService.findOne(usuallyEmploy.getEmployId());
                if (driver != null) {
                    if (driver.getId().equals(usuallyEmploy.getEmployId())) {
                        driver.setPressingName(String.valueOf(usuallyEmploy.getServiceType()));
                    }
                    driverList.add(driver);
                }
            }
            Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
            mv.addObject("page", new PageImpl<Driver>(driverList, pageable, count));

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "coupongift/{id}", method = RequestMethod.GET)
    public ModelAndView coupongift(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("member")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/coupongift");
            mv.addObject("passenger", memberService.findOnePassenger(id));
            mv.addObject("coupons", couponRuleService.listValid());

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 删除该等级并且关联的客户等级设置为空.
     */
    @RequestMapping(value = "deleteGrade/{id}", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteGrade(@PathVariable("id") Long id) {

        Map<String, Object> map = new HashMap<String, Object>();

        boolean deleteGrade = memberService.deleteGrade(id);

        if (deleteGrade) {
            map.put("success", true);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("message", "删除失败");
        }

        return map;
    }

    /**
     * 处理等级为空的客户为当前等级.
     */
    @RequestMapping(value = "disposeGrade/{id}", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> disposeGrade(@PathVariable("id") Long id) {

        Map<String, Object> map = new HashMap<String, Object>();

        boolean disposeGrade = memberService.disposeGrade(id);

        if (disposeGrade) {
            map.put("success", true);
            map.put("message", "处理成功");
        } else {
            map.put("success", false);
            map.put("message", "处理失败");
        }
        return map;
    }

    @RequestMapping(value = "findByPhone", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> findByPhone(String phone, CouponType couponType,
        @RequestParam(required = false, value = "couponTypeId") Long couponTypeId) {

        Map<String, Object> map = new HashMap<String, Object>();
        Passenger passenger = memberService.findOnePassengerByPhone(phone);
        WeixinManager weixinManager = weixinManagerService.findByPhone(phone);

        if (null != passenger) {

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            long countAll = 0;
            long countAllNotCancel = 0;
            long countMonth = 0;
            long countMonthNotCancel = 0;

            Setting setting = settingUtils.get();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date begin = calendar.getTime();
            Date end = DateUtils.addHours(begin, 24);

            if (serviceSetting.isDaijia()) {
                List<Order> orderList = orderService
                    .findTodayOrderByMember(begin, end, passenger.getId());
                map.put("orderList", orderList);

                countAll = orderService.countByMember(phone, null, null);
                countAllNotCancel = orderService.countNotCancelByMember(phone, null, null);
            }

            calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            begin = calendar.getTime();

            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            end = calendar.getTime();
            end = DateUtils.addDays(end, 24);

            if (serviceSetting.isDaijia()) {
                countMonth = orderService.countByMember(phone, begin, end);
                countMonthNotCancel = orderService.countNotCancelByMember(phone, begin, end);
            }

            if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                Enterprise enterprise = memberService
                    .findOneEnterprise(passenger.getEnterprise_id());
                if (null != enterprise) {
                    passenger.setDrawMoney(enterprise.getDrawMoney());
                }
            }
            map.put("passenger", passenger);
            try {
                List<Coupon> coupons = couponService
                    .listByPassenger(passenger.getId(), couponType, couponTypeId, null);
                map.put("coupons", coupons);
            } catch (Exception e) {
                e.printStackTrace();
                map.put("coupons", null);
            }

            map.put("countAll", countAll);
            map.put("countAllNotCancel", countAllNotCancel);
            map.put("countMonth", countMonth);
            map.put("countMonthNotCancel", countMonthNotCancel);
        } else {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            map.put("companyId", principal.getCompanyId());
        }

        map.put("weixinManager", weixinManager);

        return map;

    }

    @RequestMapping(value = "queryMemberByPhone", method = RequestMethod.GET)
    public @ResponseBody
    List<Passenger> queryMemberByPhone(String keyword) {

        List<Passenger> list = memberService.findAllPassengersByPhone(keyword);

        return list;

    }

    public boolean exists(String phone, Long id) {

        Passenger pa = memberService.findOnePassengerByPhone(phone);

        if (null != pa) {

            if (null != id && id.equals(pa.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

    private boolean EmailExists(String email, Long id) {

        Passenger passenger = memberService.findOnePassengerByEmail(email);

        if (null != passenger) {

            if (null != id && id.equals(passenger.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

    private boolean IdcardExists(String idCard, Long id) {

        Passenger passenger = memberService.findOnePassengerByIdCard(idCard);

        if (null != passenger) {

            if (null != id && id.equals(passenger.getId())) {

                return false;

            }

            return true;
        }

        return false;
    }

    @RequestMapping(value = "deletePassenger", method = RequestMethod.POST)
    public @ResponseBody
    Result<Passenger> deletePassenger(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberedit")) {
            Result<Passenger> result = new Result<Passenger>();

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            if (serviceSetting.isDaijia()) {
                List<Order> orders = orderService.findActiveByMember(id);
                if (!CollectionUtils.isEmpty(orders)) {
                    result.setSuccess(false);
                    result.setMessage("该客户还有未完成的代驾订单，不能删除。");
                    return result;
                }
            }

            if (serviceSetting.isZhuanche()) {
                Long zhuancheActive = zhuancheService.countActiveByPassenger(id);
                if (zhuancheActive > 0) {
                    result.setSuccess(false);
                    result.setMessage("该客户还有未完成的专车订单，不能删除。");
                    return result;
                }
            }

            if (serviceSetting.isPaotui()) {
                Long paotuiActive = errandService.countActiveByPassenger(id);
                if (paotuiActive > 0) {
                    result.setSuccess(false);
                    result.setMessage("该客户还有未完成的跑腿订单，不能删除。");
                    return result;
                }
            }

            if (serviceSetting.isFreight()) {
                Long freightActive = freightService.countActiveByPassenger(id);
                if (freightActive > 0) {
                    result.setSuccess(false);
                    result.setMessage("该客户还有未完成的货运订单，不能删除。");
                    return result;
                }
            }

            Passenger local = memberService.findOnePassenger(id);

            String detail = "【%s】删除了用户【" + local.getName() + "】";

            result = memberService.delete(local);

            if (result.isSuccess()) {
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteEnterprise", method = RequestMethod.POST)
    public @ResponseBody
    Result<Enterprise> deleteEnterprise(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberedit")) {
            Result<Enterprise> result = new Result<Enterprise>();

            Enterprise enterprise = memberService.findOneEnterprise(id);
            List<Passenger> plist = enterprise.getPassengers();

            boolean haveActivedOrder = false;
            for (Passenger passenger : plist) {
                List<Order> orders = orderService.findActiveByMember(passenger.getId());
                if (!CollectionUtils.isEmpty(orders)) {
                    haveActivedOrder = true;
                    break;
                }
            }

            if (haveActivedOrder) {
                result.setSuccess(false);
                result.setMessage("该企业下的客户还有未完成的订单或正在执行的订单，不能删除。");
                return result;
            }

            String detail = "【%s】删除了企业【" + enterprise.getName() + "】";

            result = memberService.deleteEnterprise(enterprise);

            if (result.isSuccess()) {
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "black", method = RequestMethod.POST)
    public @ResponseBody
    Result<Passenger> black(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberedit")) {
            Result<Passenger> result = new Result<Passenger>();

            Passenger local = memberService.findOnePassenger(id);

            String detail = "【%s】添加了黑名单用户【" + local.getName() + "】";

            result = memberService.black(local);

            if (result.isSuccess()) {
                MemberInBlackListEvent activityCheckEvent = new MemberInBlackListEvent(local, true);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);

                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "unblack", method = RequestMethod.POST)
    public @ResponseBody
    Result<Passenger> unblack(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberedit")) {

            Passenger local = memberService.findOnePassenger(id);

            String detail = "【%s】移除了黑名单用户【" + local.getName() + "】";

            Result<Passenger> result = memberService.unblack(local);

            if (result.isSuccess()) {
                MemberInBlackListEvent activityCheckEvent = new MemberInBlackListEvent(local,
                    false);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);

                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("importMember")
    @ResponseBody
    public Map<String, Object> importMember(
        @RequestParam("memberExcel") MultipartFile file) throws IOException, ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Workbook wb = null;
        try {
            wb = new HSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            wb = new XSSFWorkbook(file.getInputStream());
        }
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        Sheet sheet = wb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();// 得到总行数
        Row row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells(); //列的数量
        //Pattern pattern = Pattern.compile("^1[3-9]\\d{9}$");
        Pattern pattern = Pattern.compile("^\\+?\\d{3,13}(\\-?(\\d{6,8}?))?(\\-?(\\d{4,8}?))*$");
        List<Integer> phoneIndexs = new LinkedList<>();
        Map<Integer, Integer> repeatPhone = new HashMap<>();
        List<Passenger> list = new LinkedList<>();
        for (int i = 1; i <= rowNum; i++) {
            int j = 0;
            row = sheet.getRow(i);
            boolean flag = false;
            Passenger passenger = new Passenger();
            while (j < colNum) {
                if (row == null || row.getCell(j) == null) {
                    j++;
                    continue;
                }
                String str = ExcelUtil.getCellFormatValue(row.getCell(j)).trim();
                passenger.setCompanyName(principal.getCompanyAbbreviation());
                passenger.setCompanyId(principal.getCompanyId());
                switch (j) {
                    case 0:
                        if (StringUtils.isBlank(str)) {
                            flag = true;
                        } else {
                            passenger.setName(str);
                        }
                        break;
                    case 1:
                        if (StringUtils.isBlank(str)) {
                            flag = true;
                        } else {
                            if (pattern.matcher(str).matches()) {
                                passenger.setPhone(str);
                            } else {
                                phoneIndexs.add(i + 1);
                            }
                        }
                        break;
                }
                j++;
            }
            if (flag) {
                continue;
            }
            int length = list.size();
            int tempIndex = -1;
            if (length >= 1) {
                for (int index = 0; index < length; index++) {
                    if (StringUtils.isNotBlank(list.get(index).getPhone())) {
                        if (list.get(index).getPhone().equalsIgnoreCase(passenger.getPhone())) {
                            tempIndex = index;
                            break;
                        }
                    }
                }
            }
            if (tempIndex != -1) {
                repeatPhone.put(i + 1, tempIndex + 2);
            } else {
                if (StringUtils.isNotBlank(passenger.getPhone()) && StringUtils
                    .isNotBlank(passenger.getName())) {
                    list.add(passenger);
                }
            }
        }
        if (list.size() > 2001) {
            response.put("msg", "导入数量过大,请限制数量在2000以内");
            response.put("rowNum", list.size());
            return response;
        }
        if (list.size() <= 0) {
            response.put("msg", "Excel文件内容不正确");
            response.put("rowNum", list.size());
            return response;
        }
        if (CollectionUtils.isEmpty(phoneIndexs) && repeatPhone.isEmpty()) {
            if (!CollectionUtils.isEmpty(list)) {
                Gson gson = new Gson();
                String data = gson.toJson(list);
                Result<Map<String, Object>> mapResult = memberService.batchCreate(data);
                if (mapResult.isSuccess()) {
                    response.put("success", true);
                    response.putAll(mapResult.getResult());
                }
            }

        }
        response.put("phoneIndexs", phoneIndexs);
        if (!repeatPhone.isEmpty()) {
            response.put("repeatPhone", repeatPhone);
        }
        return response;
    }

    /**
     * 乘客上报
     *
     * @param ids
     * @param request
     * @return
     */
    @RequestMapping("checkMember")
    @ResponseBody
    public Result checkMember(
        @RequestParam("ids") Long[] ids, HttpServletRequest request) {
        Result result = new Result();
        try {
            HttpSession session = request.getSession();
            memberService.checkMember(ids, session);
            result.setSuccess(true);
            result.setMessage("成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("失败");
        }
        return result;
    }


    @RequestMapping("getCheckMemberInfo")
    @ResponseBody
    public Map<String, Object> getCheckInfo(HttpServletRequest request) {

        return (Map<String, Object>) request.getSession().getAttribute("checkMemberInfo");
    }

    @RequestMapping("uploadMember")
    @ResponseBody
    public Map<String, Object> uploadMember(
        @RequestParam("ids") Long[] ids, HttpServletRequest request) {

        Map<String, Object> stringObjectMap = memberService.uploadMember(ids);
        return stringObjectMap;
    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        dataBinder.setAutoGrowCollectionLimit(1024);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }

    @RequestMapping(value = "findOne", method = RequestMethod.GET)
    public @ResponseBody
    Passenger findOne(@RequestParam("passengerId") Long passengerId) {
        return memberService.findOnePassenger(passengerId);
    }

}
